# -*- coding: utf-8 -*-
from selenium.webdriver.support.ui import WebDriverWait
import time
from selenium.webdriver.common.keys import Keys
from selenium.webdriver.support.expected_conditions import element_to_be_clickable as EC
from selenium.webdriver.common.action_chains import ActionChains


class Base:
    # 初始化WebDriver
    def __init__(self, driver):
        self.driver = driver

    # 打开网址
    def open_url(self, url):
        self.driver.get(url)

    # 获取时间戳
    def time_nyr(self):
        return time.strftime('%Y.%m.%d.%H.%M.%S', time.localtime())

    # 时间戳截图
    def save(self):
        self.driver.save_screenshot(f'../Png/{self.time_nyr()}.png')

    # 定位方法
    def find_element(self, loc):
        try:
            WebDriverWait(self.driver, 20, 0.5).until(lambda driver: driver.find_element(*loc).is_displayed())
            return self.driver.find_element(*loc)
        except Exception as e:
            self.save()
            print('报错时间：', self.time_nyr())

    # 输入方法
    def send_keys(self, loc, data):
        self.find_element(loc).send_keys(data)

    # 点击方法
    def click(self, loc):
        self.find_element(loc).click()

    # 多窗口切换方法
    def window_handles(self):
        self.driver.switch_to.window(self.driver.window_handles[-1])

    # 键盘事件
    def keys_x(self, loc, x):
        self.find_element(loc).send_keys(Keys.CONTROL, f'{x}')

    # 鼠标事件
    def double_click(self, loc):
        ActionChains(self.driver).double_click(loc).perform()

    # 滚动条事件
    def execute_x(self, x):
        self.driver.execute_script(f'window.scrollTo(0, {x})')

